<template>
  <div>

    <div class="d-flex align-center justify-space-between mb-3">
      <div class="text-h6 font-weight-bold brand-logo">Fixed Response Management</div>
      <div class="d-flex align-center">
        <v-text-field
          v-model.trim="queryInput"
          class="mr-2"
          style="width: 280px;"
          outlined
          dense
          clearable
          hide-details
          label="Search API Path or Result JSON (e.g. /api/test or status:active)"
          append-icon="mdi-magnify"
          @keyup.enter="onSearchFromInput"
          @click:append="onSearchFromInput"
          @click:clear="onResetInput"
        />
        <v-btn class="mr-2" outlined>Export</v-btn>
        <v-btn color="primary" dark @click="openAddDialog">+ Add Fixed Response</v-btn>
      </div>
    </div>

    <v-data-table
      :headers="headers"
      :items="fixedResponses"
      :items-per-page="pageSize"
      :page.sync="pageNum"
      :server-items-length="total"
      :loading="loading"
      class="elevation-1"
      dense
      @update:page="onPageChange"
      @update:items-per-page="onPageSizeChange"
      @click:row="onRowClick"
    >
      <template v-slot:item.isActive="{ item }">
        <v-chip small :color="item.isActive ? 'green lighten-4' : 'red lighten-4'" :text-color="item.isActive ? 'green darken-2' : 'red darken-2'">
          {{ item.isActive ? 'Active' : 'Inactive' }}
        </v-chip>
      </template>
      <template v-slot:item.resultJson="{ item }">
        <span class="text-truncate" style="max-width: 200px; display: inline-block;">
          {{ item.resultJson ? item.resultJson.substring(0, 50) + '...' : '-' }}
        </span>
      </template>
      <template v-slot:item.paramHash="{ item }">
        <span class="text-truncate" style="max-width: 150px; display: inline-block;">
          {{ item.paramHash ? item.paramHash.substring(0, 20) + '...' : '-' }}
        </span>
      </template>
      <template v-slot:item.createTime="{ item }">
        {{ item.createTime ? new Date(item.createTime).toLocaleString() : '-' }}
      </template>
      <template v-slot:item.updateTime="{ item }">
        {{ item.updateTime ? new Date(item.updateTime).toLocaleString() : '-' }}
      </template>
      <template v-slot:item.actions="{ item }">
        <v-btn x-small outlined color="primary" class="mr-1" @click="openEditDialog(item)">Edit</v-btn>
        <v-btn x-small outlined color="error" @click="confirmDelete(item)">Delete</v-btn>
      </template>
    </v-data-table>

    <!-- Add/Edit Fixed Response Dialog -->
    <v-dialog v-model="dialog" max-width="720px">
      <v-card>
        <v-card-title class="font-weight-bold">{{ isEdit ? 'Edit Fixed Response' : 'Add Fixed Response' }}</v-card-title>
        <v-divider></v-divider>
        <v-card-text>
          <v-form ref="form" v-model="formValid">
            <v-text-field v-model="formModel.api" label="API Path" outlined dense :rules="[rules.required]" />
            <v-text-field v-model="formModel.paramHash" label="Parameter Hash" outlined dense :rules="[rules.required]" />
            <v-textarea 
              v-model="formModel.resultJson" 
              label="Result JSON" 
              outlined 
              dense 
              rows="8"
              :rules="[rules.required, rules.jsonFormat]"
              hint="Enter valid JSON format"
              persistent-hint
            />
            <div class="d-flex align-center mt-2">
              <v-switch v-model="formModel.isActive" inset label="Active" class="ma-0" />
            </div>
          </v-form>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-actions class="justify-end">
          <v-btn text @click="closeDialog">Cancel</v-btn>
          <v-btn color="primary" dark @click="submitFixedResponse">Save</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Detail Dialog -->
    <v-dialog v-model="detailDialog" max-width="800px">
      <v-card>
        <v-card-title class="font-weight-bold">Fixed Response Detail</v-card-title>
        <v-divider></v-divider>
        <v-card-text>
          <v-skeleton-loader v-if="detailLoading" type="article" />
          <div v-else>
            <div class="mb-3">
              <div><strong>ID:</strong> {{ detailFixedResponse.id }}</div>
              <div><strong>API Path:</strong> {{ detailFixedResponse.api }}</div>
              <div><strong>Parameter Hash:</strong> {{ detailFixedResponse.paramHash || '-' }}</div>
              <div><strong>Status:</strong> {{ detailFixedResponse.isActive ? 'Active' : 'Inactive' }}</div>
              <div><strong>Create Time:</strong> {{ detailFixedResponse.createTime ? new Date(detailFixedResponse.createTime).toLocaleString() : '-' }}</div>
              <div><strong>Update Time:</strong> {{ detailFixedResponse.updateTime ? new Date(detailFixedResponse.updateTime).toLocaleString() : '-' }}</div>
            </div>
            <div>
              <div class="subtitle-2 font-weight-bold mb-2">Result JSON</div>
              <v-card outlined>
                <v-card-text>
                  <pre class="json-content">{{ formatJson(detailFixedResponse.resultJson) }}</pre>
                </v-card-text>
              </v-card>
            </div>
          </div>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-actions class="justify-end">
          <v-btn text @click="detailDialog=false">Close</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
export default {
  name: 'FixedResponsePage',
  data() {
    return {
      headers: [
        { text: 'ID', value: 'id' },
        { text: 'API PATH', value: 'api' },
        { text: 'PARAM HASH', value: 'paramHash' },
        { text: 'RESULT JSON', value: 'resultJson' },
        { text: 'STATUS', value: 'isActive' },
        { text: 'CREATE TIME', value: 'createTime' },
        { text: 'UPDATE TIME', value: 'updateTime' },
        { text: 'ACTIONS', value: 'actions', sortable: false }
      ],
      fixedResponses: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      loading: false,
      queryInput: '',
      query: { api: '', resultJson: '', isActive: '' },
      dialog: false,
      isEdit: false,
      formValid: false,
      formModel: { 
        id: '', 
        api: '', 
        paramHash: '', 
        resultJson: '{}', 
        isActive: true 
      },
      detailDialog: false,
      detailLoading: false,
      detailFixedResponse: {},
      rules: { 
        required: v => !!(v && String(v).trim()) || 'Required',
        jsonFormat: v => {
          if (!v) return 'Required'
          try {
            JSON.parse(v)
            return true
          } catch (e) {
            return 'Invalid JSON format'
          }
        }
      }
    }
  },
  created() {
    this.fetchFixedResponses()
  },
  methods: {
    async fetchFixedResponses() {
      this.loading = true
      try {
        const q = { ...this.query }
        Object.keys(q).forEach(k => { if (q[k] === '' || q[k] === null || typeof q[k] === 'undefined') delete q[k] })
        const res = await this.$api.fixedResponse.getFixedResponses({ pageNum: this.pageNum, pageSize: this.pageSize, ...q })
        const payload = res && (res.data || res)
        this.fixedResponses = payload.list || payload.items || []
        this.total = Number(payload.total || payload.totalCount || 0)
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to fetch fixed responses', e)
      } finally {
        this.loading = false
      }
    },
    onSearch() { this.pageNum = 1; this.fetchFixedResponses() },
    onReset() { this.query = { api: '', resultJson: '', isActive: '' }; this.pageNum = 1; this.fetchFixedResponses() },
    onSearchFromInput() {
      const params = this.parseQueryInput(this.queryInput)
      this.query = { api: '', resultJson: '', isActive: '', ...params }
      this.pageNum = 1
      this.fetchFixedResponses()
    },
    onResetInput() {
      this.queryInput = ''
      this.onReset()
    },
    parseQueryInput(input) {
      const params = {}
      if (!input || !input.trim()) return params
      const tokens = input.trim().split(/\s+/)
      tokens.forEach(t => {
        const idx = t.indexOf(':')
        if (idx > 0) {
          const key = t.slice(0, idx).toLowerCase()
          const valRaw = t.slice(idx + 1)
          const val = valRaw === 'true' ? true : valRaw === 'false' ? false : valRaw
          if (['path', 'api'].includes(key)) params.api = val
          else if (['json', 'result', 'resultjson'].includes(key)) params.resultJson = val
          else if (['active', 'status', 'isactive'].includes(key)) params.isActive = val
        } else {
          // Bare keyword - try to match both API and resultJson
          const searchTerm = t
          if (!params.api && !params.resultJson) {
            // If no specific field is set, search both API and resultJson
            params.api = searchTerm
            params.resultJson = searchTerm
          } else if (!params.api) {
            params.api = searchTerm
          } else if (!params.resultJson) {
            params.resultJson = searchTerm
          }
        }
      })
      return params
    },
    async confirmDelete(item) {
      if (!item || !item.id) return
      const ok = window.confirm(`Delete fixed response for "${item.api}"?`)
      if (!ok) return
      try {
        await this.$api.fixedResponse.deleteFixedResponse(item.id)
        this.fetchFixedResponses()
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to delete fixed response', e)
      }
    },
    onPageChange(p) { this.pageNum = p; this.fetchFixedResponses() },
    onPageSizeChange(size) { this.pageSize = size; this.pageNum = 1; this.fetchFixedResponses() },
    openAddDialog() {
      this.isEdit = false
      this.formModel = { 
        id: '', 
        api: '', 
        paramHash: '', 
        resultJson: '{}', 
        isActive: true 
      }
      this.dialog = true
    },
    openEditDialog(item) {
      this.isEdit = true
      this.formModel = { 
        id: item.id, 
        api: item.api, 
        paramHash: item.paramHash || '', 
        resultJson: typeof item.resultJson === 'string' ? item.resultJson : JSON.stringify(item.resultJson, null, 2), 
        isActive: !!item.isActive 
      }
      this.dialog = true
    },
    closeDialog() {
      this.dialog = false
      this.$nextTick(() => { if (this.$refs.form) this.$refs.form.resetValidation() })
    },
    async submitFixedResponse() {
      if (!this.$refs.form || !this.$refs.form.validate()) return
      try {
        const resultJsonData = JSON.parse(this.formModel.resultJson)
        if (this.isEdit) {
          await this.$api.fixedResponse.updateFixedResponse(this.formModel.id, {
            api: this.formModel.api,
            paramHash: this.formModel.paramHash,
            resultJson: resultJsonData,
            isActive: !!this.formModel.isActive
          })
        } else {
          await this.$api.fixedResponse.createFixedResponse({
            api: this.formModel.api,
            paramHash: this.formModel.paramHash,
            resultJson: resultJsonData,
            isActive: !!this.formModel.isActive
          })
        }
        this.closeDialog()
        this.fetchFixedResponses()
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to submit fixed response', e)
      }
    },
    onRowClick(item, event) {
      if (event && event.detail >= 2) {
        this.openDetail(item)
      }
    },
    async openDetail(item) {
      this.detailDialog = true
      this.detailLoading = true
      this.detailFixedResponse = {}
      try {
        const fixedResponseDetail = await this.$api.fixedResponse.getFixedResponseById(item.id)
        this.detailFixedResponse = (fixedResponseDetail && (fixedResponseDetail.data || fixedResponseDetail)) || item
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to load fixed response detail', e)
      } finally {
        this.detailLoading = false
      }
    },
    formatJson(json) {
      if (!json) return ''
      try {
        // 如果已经是字符串，先解析再格式化
        const parsed = typeof json === 'string' ? JSON.parse(json) : json
        return JSON.stringify(parsed, null, 2)
      } catch (e) {
        return String(json)
      }
    }
  }
}
</script>

<style scoped>
.json-content {
  background-color: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
  max-height: 300px;
  overflow-y: auto;
}
</style>